<template>
  <div class="banners-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>轮播图管理</span>
          <el-button type="primary" @click="handleAdd">新增轮播图</el-button>
        </div>
      </template>
      
      <div class="toolbar">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input v-model="queryParams.keyword" placeholder="请输入标题关键词" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table :data="bannerList" v-loading="loading" border>
        <el-table-column prop="title" label="标题" />
        <el-table-column label="图片" width="200">
          <template #default="scope">
            <el-image
              :src="scope.row.image"
              :preview-src-list="[scope.row.image]"
              fit="cover"
              class="banner-image"
            />
          </template>
        </el-table-column>
        <el-table-column prop="link" label="链接" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" align="center">
          <template #default="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              :loading="scope.row.statusLoading"
              @change="() => handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="220" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="图片" prop="image">
          <el-upload
            class="banner-uploader"
            :action="uploadAction"
            name="file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-progress="handleUploadProgress"
            :before-upload="beforeUpload"
            :headers="uploadHeaders"
            :http-request="customUpload"
          >
            <el-image
              v-if="form.image"
              :src="form.image"
              fit="contain"
              style="width: 300px; height: 160px"
            />
            <el-icon v-else class="banner-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="el-upload__tip">
            建议尺寸: 750x400像素，支持jpg、png格式，大小不超过2MB
            <el-button size="small" type="primary" link @click="testUploadUrl">测试上传接口</el-button>
          </div>
          <div v-if="form.image" style="margin-top: 10px; font-size: 12px; color: #666;">
            当前图片URL: {{ form.image }}
            <el-button size="small" link type="primary" @click="checkImageExists(form.image)">
              检查图片是否可访问
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="关联商品" prop="productId">
          <el-select 
            v-model="form.productId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入商品名称搜索"
            :remote-method="searchProducts"
            :loading="productsLoading"
            @change="handleProductChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <div style="display: flex; align-items: center;">
                <el-image
                  v-if="item.cover"
                  :src="item.cover"
                  style="width: 40px; height: 40px; margin-right: 10px; object-fit: cover;"
                ></el-image>
                <div>
                  <div>{{ item.name }}</div>
                  <div style="font-size: 12px; color: #999;">¥{{ item.price }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接地址" />
          <div class="el-upload__tip" v-if="form.productId">
            已自动生成商品链接: <span style="color: #409EFF;">{{ form.link }}</span>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus, Edit, Delete } from '@element-plus/icons-vue'
import { 
  getBannerList, 
  createBanner, 
  updateBanner, 
  deleteBanner, 
  updateBannerStatus, 
  uploadBannerImage,
  updateBannerSort 
} from '@/api/banner'
import { getProducts, getProductDetail } from '@/api/products'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const bannerList = ref([])
const currentId = ref(null)
const formRef = ref(null)

// 上传地址
const baseApiUrl = import.meta.env.VITE_API_URL || '';
console.log('基础API URL:', baseApiUrl);
const uploadAction = '/api/admin/upload/banner';
console.log('最终上传路径:', uploadAction);

// 对话框标题
const dialogTitle = computed(() => currentId.value ? '编辑轮播图' : '添加轮播图')

// 添加商品相关状态
const productOptions = ref([])
const productsLoading = ref(false)

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
  status: undefined
})

// 分页总数
const total = ref(0)

// 表单数据
const form = reactive({
  title: '',
  image: '',
  link: '',
  sort: 0,
  status: 1,
  productId: null
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 32, message: '标题长度不能超过32个字符', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传图片', trigger: 'change' }
  ],
  link: [
    { required: false, message: '请输入链接', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value && !form.productId) {
          callback(new Error('请输入链接或选择关联商品'))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'change' }
  ]
}

// 添加上传相关变量和方法
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 上传进度处理
const handleUploadProgress = (event, file) => {
  console.log('上传进度:', event.percent)
  console.log('上传文件状态:', file)
}

// 查询轮播图列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: queryParams.page,
      pageSize: queryParams.pageSize,
      keyword: queryParams.keyword,
      status: queryParams.status
    }
    
    // 过滤掉undefined和空字符串
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })
    
    console.log('查询参数:', params)
    const result = await getBannerList(params)
    console.log('获取轮播图列表返回数据:', result)
    
    // 兼容不同的API返回格式
    if (result && result.data) {
      // 标准格式: { data: [...], total: X }
      bannerList.value = result.data
      total.value = result.total || 0
    } else if (result && result.list) {
      // 另一种格式: { list: [...], total: X }
      bannerList.value = result.list
      total.value = result.total || 0
    } else if (Array.isArray(result)) {
      // 直接返回数组
      bannerList.value = result
      total.value = result.length
    } else {
      // 无法识别的格式
      bannerList.value = []
      total.value = 0
      console.warn('无法识别的API返回格式:', result)
    }
    
    console.log('处理后的轮播图列表:', bannerList.value)
    console.log('总数:', total.value)
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
    bannerList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.page = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.status = undefined
  queryParams.page = 1
  fetchData()
}

// 处理每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchData()
}

// 商品搜索函数
const searchProducts = async (query) => {
  if (query.length < 1) return
  
  productsLoading.value = true
  try {
    const params = {
      keyword: query,
      pageSize: 20,
      page: 1,
      status: 1 // 只搜索上架的商品
    }
    
    const res = await getProducts(params)
    console.log('商品搜索结果:', res)
    
    if (res && res.list) {
      productOptions.value = res.list
    } else {
      productOptions.value = []
    }
  } catch (error) {
    console.error('搜索商品失败:', error)
    ElMessage.error('搜索商品失败')
  } finally {
    productsLoading.value = false
  }
}

// 商品选择变更处理
const handleProductChange = async (productId) => {
  if (!productId) {
    return
  }
  
  try {
    // 获取商品详情
    const productData = await getProductDetail(productId)
    console.log('选中商品详情:', productData)
    
    if (productData) {
      // 生成适用于小程序的商品详情页链接
      form.link = `/pages/product/detail?id=${productId}`
      
      // 如果没有设置标题，则使用商品名称作为轮播图标题
      if (!form.title) {
        form.title = productData.name
      }
      
      ElMessage.success('已自动生成商品链接')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.title = ''
  form.image = ''
  form.link = ''
  form.sort = 0
  form.status = 1
  form.productId = null
  currentId.value = null
}

// 添加轮播图
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = async (row) => {
  resetForm()
  currentId.value = row.id
  
  // 复制基本属性
  Object.assign(form, row)
  
  // 如果有链接，尝试解析出商品ID
  if (row.link && row.link.includes('/pages/product/detail?id=')) {
    try {
      const productId = row.link.split('id=')[1].split('&')[0]
      if (productId) {
        form.productId = parseInt(productId, 10)
        // 根据商品ID获取商品信息，将其加入选项中
        await loadProductById(form.productId)
      }
    } catch (error) {
      console.error('解析商品ID失败:', error)
    }
  }
  
  dialogVisible.value = true
}

// 根据ID加载商品并添加到选项中
const loadProductById = async (productId) => {
  if (!productId) return
  
  try {
    const productData = await getProductDetail(productId)
    if (productData) {
      // 确保商品存在于选项列表中
      const exists = productOptions.value.some(item => item.id === productId)
      if (!exists) {
        productOptions.value.push(productData)
      }
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
  }
}

// 修改状态
const handleChangeStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    await updateBannerStatus(row.id, newStatus)
    ElMessage.success('状态修改成功')
    fetchData()
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('修改状态失败')
  }
}

// 通过开关修改状态
const handleStatusChange = async (row) => {
  // 添加状态loading标记
  row.statusLoading = true
  try {
    await updateBannerStatus(row.id, row.status)
    ElMessage.success('状态修改成功')
  } catch (error) {
    console.error('修改状态失败:', error)
    ElMessage.error('修改状态失败')
    // 发生错误时恢复原状态
    row.status = row.status === 1 ? 0 : 1
  } finally {
    row.statusLoading = false
  }
}

// 删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBanner(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = /^image\/(jpeg|png|jpg)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  console.log('上传文件:', file)
  console.log('文件类型:', file.type)
  console.log('文件大小:', file.size)
  console.log('上传URL:', uploadAction)
  console.log('上传头信息:', uploadHeaders)

  if (!isImage) {
    ElMessage.error('只能上传jpg/png格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  
  // 创建临时img元素，测试图片是否可以正常加载
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = (e) => {
    const img = new Image()
    img.src = e.target.result
    img.onload = () => {
      console.log('图片加载成功，尺寸:', img.width, 'x', img.height)
    }
    img.onerror = () => {
      console.error('图片加载失败，可能不是有效的图片文件')
      ElMessage.warning('图片加载失败，可能不是有效的图片文件')
    }
  }
  
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  console.log('上传成功，原始响应:', response);
  console.log('文件对象:', file);
  console.log('文件列表:', fileList);
  
  try {
    // 尝试解析响应数据
    let data = response;
    if (typeof response === 'string') {
      data = JSON.parse(response);
    }
    
    console.log('解析后的响应数据:', data);
    
    // 获取图片URL
    let imageUrl = null;
    
    // 检查响应结构，适配不同的返回格式
    if (data && (data.code === 0 || data.code === 200) && data.data) {
      // 标准格式返回
      if (data.data.url) {
        imageUrl = data.data.url;
      } else if (data.data.path) {
        // 如果只有path，构造完整URL
        const path = data.data.path;
        imageUrl = path.startsWith('/') ? path : `/${path}`;
      } else if (typeof data.data === 'string') {
        // 直接返回字符串作为URL
        imageUrl = data.data;
      }
    } else if (data && data.url) {
      // 直接返回url的格式
      imageUrl = data.url;
    } else if (typeof data === 'string') {
      // 服务器可能直接返回了URL字符串
      imageUrl = data;
    }
    
    console.log('提取的图片URL:', imageUrl);
    
    if (!imageUrl) {
      console.error('无法从响应中提取图片URL:', data);
      ElMessage.error('上传失败：无法获取图片URL');
      return;
    }
    
    // 确保URL是绝对路径
    if (imageUrl.startsWith('/')) {
      const baseUrl = window.location.origin;
      imageUrl = `${baseUrl}${imageUrl}`;
      console.log('转换为绝对路径URL:', imageUrl);
    }
    
    console.log('最终图片URL:', imageUrl);
    
    // 设置轮播图图片URL
    form.image = imageUrl;
    ElMessage.success('上传成功');
    
    // 验证图片是否可以正常加载
    checkImageExists(imageUrl);
  } catch (error) {
    console.error('处理上传响应时出错:', error);
    ElMessage.error('处理上传响应失败');
  }
}

// 上传错误处理
const handleUploadError = (error, file, fileList) => {
  console.error('上传失败:', error)
  console.error('上传失败的文件:', file)
  console.error('当前文件列表:', fileList)
  
  // 尝试解析错误信息
  let errorMsg = '上传失败: '
  
  try {
    if (typeof error === 'string') {
      errorMsg += error
    } else if (error && error.message) {
      errorMsg += error.message
    } else if (error && error.status) {
      errorMsg += `服务器返回错误状态码: ${error.status}`
      if (error.status === 404) {
        errorMsg = '上传接口不存在，请检查服务器配置'
      } else if (error.status === 500) {
        errorMsg = '服务器内部错误'
      }
    } else if (error && error.response) {
      // 解析响应
      const responseText = error.response.data || error.response.statusText || '未知错误'
      errorMsg += `${error.response.status} - ${responseText}`
    } else {
      errorMsg += JSON.stringify(error) || '未知错误'
    }
    
    // 检查网络连接问题
    if (!navigator.onLine) {
      errorMsg = '网络连接已断开，请检查网络连接后重试'
    }
  } catch (parseError) {
    console.error('解析上传错误时出错:', parseError)
    errorMsg += '无法解析错误详情'
  }
  
  ElMessage.error(errorMsg)
}

// 检查图片是否可以正常加载
const checkImageExists = (url) => {
  if (!url) return
  
  const img = new Image()
  img.onload = () => {
    console.log('图片验证成功，可以正常加载:', url)
  }
  img.onerror = () => {
    console.error('图片验证失败，无法正常加载:', url)
    ElMessage.warning('图片已上传，但可能无法正常显示，请检查图片路径')
  }
  img.src = url
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      // 准备提交数据，去除productId字段（后端不需要）
      const submitData = {
        title: form.title,
        image: form.image,
        link: form.link,
        sort: form.sort,
        status: form.status
      }
      
      try {
        if (currentId.value) {
          await updateBanner(currentId.value, submitData)
          ElMessage.success('更新成功')
        } else {
          await createBanner(submitData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error(currentId.value ? '更新失败:' : '添加失败:', error)
        ElMessage.error(currentId.value ? '更新失败' : '添加失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 添加自定义上传方法
const customUpload = (options) => {
  const { action, file, onSuccess, onError, onProgress, headers } = options;
  
  // 构建正确的上传URL，避免undefined路径问题
  const uploadUrl = `/api/admin/upload/banner`;
  
  console.log('开始自定义上传:', {
    requestUrl: uploadUrl,
    originalAction: action,
    filename: file.name,
    fileType: file.type,
    fileSize: file.size,
    headers
  });
  
  // 创建FormData对象
  const formData = new FormData();
  formData.append('file', file);
  
  // 使用XMLHttpRequest进行上传
  const xhr = new XMLHttpRequest();
  
  // 监听上传进度
  xhr.upload.addEventListener('progress', (e) => {
    if (e.lengthComputable) {
      const percent = Math.round((e.loaded * 100) / e.total);
      console.log('上传进度:', percent);
      onProgress({ percent });
    }
  });
  
  // 请求完成回调
  xhr.addEventListener('load', () => {
    if (xhr.status >= 200 && xhr.status < 300) {
      try {
        const response = JSON.parse(xhr.responseText);
        console.log('上传成功，服务器响应:', response);
        onSuccess(response);
      } catch (error) {
        console.error('解析响应失败:', error, xhr.responseText);
        onError(new Error('响应解析失败'));
      }
    } else {
      console.error('上传失败，状态码:', xhr.status, xhr.statusText);
      onError(new Error(`上传失败: ${xhr.status} ${xhr.statusText}`));
    }
  });
  
  // 请求错误回调
  xhr.addEventListener('error', () => {
    console.error('上传请求发生错误');
    onError(new Error('网络错误，上传失败'));
  });
  
  // 请求中止回调
  xhr.addEventListener('abort', () => {
    console.warn('上传请求被中止');
    onError(new Error('上传已取消'));
  });
  
  // 开始上传
  xhr.open('POST', uploadUrl, true);
  
  // 设置请求头
  if (headers) {
    Object.keys(headers).forEach(key => {
      xhr.setRequestHeader(key, headers[key]);
    });
  }
  
  xhr.send(formData);
  
  // 返回上传控制器
  return {
    abort() {
      xhr.abort();
      console.log('上传已手动中止');
    }
  };
}

// 添加测试上传路径的函数
const testUploadUrl = () => {
  const testUrl = `/api/admin/upload/banner`;
  console.log('测试上传URL:', testUrl);
  
  // 创建一个fetch请求来测试上传接口是否可用
  fetch(testUrl, {
    method: 'OPTIONS',
    headers: {
      'Content-Type': 'application/json',
      ...uploadHeaders
    }
  })
  .then(response => {
    console.log('上传接口测试响应状态:', response.status);
    if (response.ok) {
      ElMessage.success('上传接口可用');
    } else {
      ElMessage.warning(`上传接口返回状态码: ${response.status}`);
    }
    return response.text();
  })
  .then(text => {
    console.log('上传接口测试响应内容:', text);
  })
  .catch(error => {
    console.error('上传接口测试失败:', error);
    ElMessage.error(`上传接口测试失败: ${error.message}`);
  });
}

// 获取热门商品
const fetchHotProducts = async () => {
  productsLoading.value = true
  try {
    const params = {
      pageSize: 10,
      page: 1,
      status: 1,
      orderBy: 'sales' // 假设有销量排序
    }
    
    const res = await getProducts(params)
    console.log('热门商品:', res)
    
    if (res && res.list) {
      productOptions.value = res.list
    }
  } catch (error) {
    console.error('获取热门商品失败:', error)
  } finally {
    productsLoading.value = false
  }
}

onMounted(() => {
  fetchData()
  fetchHotProducts() // 获取热门商品作为初始选项
})
</script>

<style scoped>
.banners-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.banner-image {
  width: 160px;
  height: 80px;
  border-radius: 4px;
}

.banner-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 300px;
  height: 160px;
}

.banner-uploader:hover {
  border-color: #409eff;
}

.banner-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 7px;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 工具栏样式 */
.toolbar {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.sort-control {
  display: flex;
  align-items: center;
}

.sort-value {
  margin: 0 10px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.operation-buttons .el-button {
  padding: 5px 10px;
  margin: 2px 0;
}

.operation-buttons .el-icon {
  margin-right: 2px;
}
</style> 